package com.mjgy.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;

import com.common.utils.R;
import com.common.utils.SpringContextUtils;
import com.google.gson.Gson;
import com.mjgy.entity.DeviceCodeEntity;
import com.mjgy.entity.MUserEntity;
import com.mjgy.entity.TokenEntity;
import com.mjgy.service.TokenService;

/**
* @Description: token拦截器
* @author LGC
* @date 2018年9月19日
* @version V1.0
*/
public class TokenFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String token = getRequestToken((HttpServletRequest) request);
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		if(StringUtils.isBlank(token)) {
			String json = new Gson().toJson(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
			httpResponse.getWriter().print(json);
		} else {
			TokenService service = (TokenService) SpringContextUtils.getBean("tokenServiceTmp");
			// 根据token，查询用户信息
			TokenEntity tokenEntity = service.getToken(token);
			// token失效
			if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
				String json = new Gson().toJson(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
				httpResponse.getWriter().print(json);
			} else {
//				Long userId = tokenEntity.getUserId();
//				MUserEntity user = service.getUserById(userId);
//				if(user == null) {
//					String json = new Gson().toJson(R.error(HttpStatus.SC_PAYMENT_REQUIRED, "user not found"));
//					httpResponse.getWriter().print(json);
//					return;
//				} else {
//					boolean flag = true;
//					
//					if(!user.getStatus()) {
//						String json = new Gson().toJson(R.error(HttpStatus.SC_PAYMENT_REQUIRED, "user bean freeze"));
//						httpResponse.getWriter().print(json);
//						return;
//					} else {
//						List<DeviceCodeEntity> deviceCodes = service.findByUserId(user.getId());
//						for(DeviceCodeEntity deviceCode : deviceCodes) {
//							if(!deviceCode.isStatus()) {
//								flag = false;
//								String json = new Gson().toJson(R.error(HttpStatus.SC_PAYMENT_REQUIRED, "deviceCode bean ban"));
//								httpResponse.getWriter().print(json);
//								break;
//							}
//						}
//					}
//					
//					if(flag) {
//						System.out.println("测试拦截");
//						chain.doFilter(request, response);
//					}
//				}
				
				chain.doFilter(request, response);
			}
		}
	}
	
	/**
	 * 获取请求中的token
	 * 
	 * @param httpRequest
	 * @return
	 */
	private String getRequestToken(HttpServletRequest httpRequest) {
		// 从header中获取token
		String token = httpRequest.getHeader("token");
		
		// 如果header中不存在token，则从参数中获取token
		if(StringUtils.isBlank(token)) {
			token = httpRequest.getParameter("token");
		}
		return token;
	}

}
